﻿using System;
using System.Collections.Generic;
using System.Text;
using RemoteTestRunner.Contracts;
using System.IO;
using System.Xml.Serialization;
using System.Diagnostics;

namespace RemoteTestRunner.DataAccess
{
    public class ProjectDataAccess
    {

        private string _dataPath;

        public ProjectDataAccess(string path)
        {
            _dataPath = path;
            //this.Load();
        }

        //private void Load()
        //{
        //    throw new NotImplementedException();
        //}

        public List<Project> GetProjects()
        {
            if (!File.Exists(_dataPath))
            {
                List<Project> emptyProjects = new List<Project>();
                SaveProjects(emptyProjects);
            }

            using (var fileStream = File.OpenRead(_dataPath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Project>));
                var projects = serializer.Deserialize(fileStream) as List<Project>;
                return projects;
            }
            //var projects = new List<Project>();
            //var project = new Project { Name = "Project 1", Id = 0 };
            //var test1 = new Test { Name = "Test 1", Id = 0, AssemblyPath = @"C:\Codeplex\rtr\TestData\RemoteTestRunnerDemo.dll" };
            //var test2 = new Test { Name = "Test 2", Id = 1, AssemblyPath = @"C:\Codeplex\rtr\TestData\RemoteTestRunnerDemo.dll" };
            //project.Tests.Add(test1);
            //project.Tests.Add(test2);
            //projects.Add(project);
            //return projects;
        }

        public void SaveProjects(IList<Project> projects)
        {
            using (var fileStream = File.OpenWrite(_dataPath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Project>));
                serializer.Serialize(fileStream, projects);
                fileStream.Flush();
                fileStream.Close();
            }
        }
    }
}
